package com.ikingtech.framework.sdk.sms.embedded.core.sanyihengxin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.enums.sms.SmsPlatformTypeEnum;
import com.ikingtech.framework.sdk.sms.embedded.AbstractSmsRequest;
import com.ikingtech.framework.sdk.sms.embedded.SmsSendArgs;
import com.ikingtech.framework.sdk.sms.embedded.SmsTemplateInfo;
import com.ikingtech.framework.sdk.sms.embedded.core.sanyihengxin.request.SanYiHengXinSendMessageOneToOneParam;
import com.ikingtech.framework.sdk.sms.embedded.core.sanyihengxin.response.SanYiHengXinResponse;
import com.ikingtech.framework.sdk.utils.Tools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class SanYiHengXinSmsRequest extends AbstractSmsRequest {

    @Override
    public void send(SmsSendArgs args) {
        SanYiHengXinSendMessageOneToOneParam param = new SanYiHengXinSendMessageOneToOneParam();
        param.setUserName(this.config.getAppId());
        SanYiHengXinSendMessageOneToOneParam.Message message = new SanYiHengXinSendMessageOneToOneParam.Message();
        message.setPhone(Tools.Encrypt.aes(args.getPhone(), this.config.getAppSecret()));
        message.setContent(Tools.Encrypt.aes(args.getContent(), this.config.getAppSecret()));
        param.setMessageList(Tools.Coll.newList(message));
        param.setTimestamp(System.currentTimeMillis());
        param.setSign(Tools.Http.md5Sign(this.config.getAppId(), Long.toString(param.getTimestamp()), Tools.Encrypt.md5(this.config.getAppKey().getBytes(Charset.defaultCharset()))));
        String resultStr = Tools.Http.post(this.config.getEndpoint() + "/sms/api/sendMessageOne", Tools.Json.toJsonStr(param));
        if (Tools.Str.isBlank(resultStr)) {
            throw new FrameworkException("[SMS][三一恒信]send sms with blank result");
        }
        SanYiHengXinResponse res = Tools.Json.toBean(resultStr, new TypeReference<>() {
        });
        if (null == res) {
            throw new FrameworkException("[SMS][三一恒信]send sms without blank");
        }
        if (res.fail()) {
            throw new FrameworkException(Tools.Str.format("[SMS][三一恒信]send sms send fail[args = {}][result = {}]", args, res));
        }
    }

    @Override
    public List<SmsTemplateInfo> listTemplate() {
        throw new FrameworkException("不支持的操作");
    }

    @Override
    public SmsPlatformTypeEnum platform() {
        return SmsPlatformTypeEnum.SAN_YI_HENG_XIN;
    }
}
